<?php

namespace Org\Util\ZiGong;

use Org\Util\ApiInterface;


class ApiServer implements ApiInterface
{
	public $apiUrl 	= 'http://192.168.114.99:8078/HisService.asmx?WSDL';

	public $timeout = 20;

	public $hospitalId = '48';
    
    /**
     * @uses    实例化对象时设置参数
     * @param   $apiUrl        Api接口地址
     * @param   $hospitalId   医院key
     * @param   $timeout       超时时间
     * @author  Duanhy
     */
	function __construct($apiUrl , $hospitalId , $timeout = 10)
	{
		$this->apiUrl 	  = $apiUrl;
		$timeout && $this->timeout = $timeout;
		$this->hospitalId = $hospitalId;
	}
    /**
     * 请求His API
     *
     *   使用SoapClient请求HIS webservice接口
     *
     * @param String $Flag 类型
     * @param String $Content xml请求内容
     * @param String $Result_K 返回xml中的跟节点key
     *
     * @return array
     */

    private function soapGetDate($Flag, $Content, $Result_K){
//        $this->isFormal = ($_SERVER['SERVER_NAME']!="localhost" && "histest.mobimedical.cn"!=$_SERVER['SERVER_NAME']);
        $this->isFormal = false;

        if (!$this->soap) {
            $this->soap = new \SoapClient($this->apiUrl, array("connection_timeout" => 15));
        }
        try {

            /* 正式环境 */
            if ($this->isFormal) {
                //专线接口,走平台
                try {
                    $result = $this->soap->Weixin(array("Flag"=>$Flag,"info"=>$Content));
                } catch (\Exception $e) {
                    $fileContent    = $Content."\n".$e->getMessage();
                    $dir            = "soapGetDate/";
                    \Org\Util\File::createDir($dir);
                    file_put_contents($dir.$Flag."_error.txt", $fileContent);
                    return array('ResultCode'=>-1, "ErrorMsg"=>"系统异常，请稍后重试21！");
                }
                $Result_K = "Weixin".Result;

                /* 测试环境 */
            } else {
                $result = $this->soap->$Flag(array("info"=>$Content));
                /* 记录请求日志   */
                $fileContent = $Content."\r".var_export($result,true);
                $dir = "soapGetDate/".date("Y-m-d")."/".$Flag."/";
                $filename = date("H_i_s")."_".rand(10000, 99999);
                writeLog($dir, $filename, $fileContent);

                return json_decode(json_encode((array) simplexml_load_string($result->$Result_K)), true);
            }


        } catch (\Exception $e) {
            /* 记录请求异常日志  */
            $fileContent = $Content."\n".$e->getMessage();
            $dir = "soapGetDate/".date("Y-m-d")."/".$Flag."/";
            $filename = date("H_i_s")."_error";
            writeLog($dir, $filename, $fileContent);
            return array('ResultCode'=>-1,"ErrorMsg"=>"系统异常，请稍后重试22！");
            exit;
        }
    }

    /**
     * 确认挂号 (锁号)
     * @param $act      '取号锁号 --类型'
     * @param $doc_id   '值班医生id'
     * @param $data     '时间'
     * @param $period   '上午或是下午'
     * @param $fee      '挂号金额'
     */
    public function registrationAjax($param){

        $act        = $param['act'];
        $doc_id     = $param['docHisId'];
        $date       = $param['date'];
        $date       = date('Y.m.d',strtotime($date));
        $period     = $param['period'];
        $fee        = $param['fee'];

        $Content    = "<Request><Act>".$act."</Act><DocId>".$doc_id."</DocId><Date>".$date."</Date><Period>".$period."</Period></Request>";
        $searchKey  = "Get_Registration";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        if ($result['ResultCode'] == 0) {
            $returnArr['code']          = 200;
            $returnArr['status']        = 1;
            $returnArr['errorMsg']      = "";
            $result['Data']['result']   = $result['Data']['Result'];
            $result['Data']['fee']      = $fee;
            $returnArr['data']          = $result['Data'];
        } else {
            $returnArr['code']          = 401;
            $returnArr['status']        = 2;
            $returnArr['errorMsg']      = $result['ResultMsg'];
            $returnArr['data']          = array();
        }
        return $returnArr;
    }
    /**
     * 挂号支付确认(取号)
     * @param $data     '时间'
     * @param $apptid   '号源编码(锁号)'
     * @param $cardNO   '就诊卡号'
     * @param $bankNo   '交易流水号'
     * @param $fee      '挂号金额'
     */

    public function registrationFetchAjax($param){

        $date       = $param['date'];
        $apptId     = $param['ApptId'];
        $cardNo     = $param['cardNo'];
        $bank_no    = $param['transaction_id'];
        $fee        = $param['fee'];

        $Content    ='<Request><Act>fetch</Act><ApptId>'.$apptId.'</ApptId><CardNo>'.$cardNo.'</CardNo><BillNo>'.$bank_no.'</BillNo><PayName>微信支付</PayName><Fee>'.$fee.'</Fee></Request>';
        $searchKey  = "Get_Registration";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        //数组元素转换
        $year       = substr($date, 0,4);
        $month      = substr($date, 5,2);
        $day        = substr($date, 8,2);
        $data['RegYear']    = $year;
        $data['RegMonth']   = $month;
        $data['RegDay']     = $day;
        $data['date']       = $date;
        $data['date']       = $result['Data']['Date'];
        $data['serNo']      = $result['Data']['SerNo'];
        $data['apptId']     = $result['Data']['ApptId'];
        $data['patName']    = $result['Data']['PatName'];
        $data['docName']    = $result['Data']['DocName'];
        $data['queueNo']    = $result['Data']['QueueNo'];
        $data['address']    = $result['Data']['Address'];
        $data['regType']    = $result['Data']['DeptName'];
        $data['LocInfo']    = "自贡妇幼保健院";
        $data['fee']        = $result['Data']['Fee'];
        $data['invoiceNo']  = $result['Data']['InvoiceNo'];
        $data['TimeInfo']   = !empty($result['Data']['TimeInfo'])?$result['Data']['TimeInfo']:"请于" . $year . "年" . $month . "月" . $day . " 日" . "前来就诊(就诊时请务必出示就诊卡，并告知医务人员是通过微信挂号的)";

        if ($result['ResultCode'] == 0) {
            $returnArr['code']         = 200;
            $returnArr['status']        = 1;
            $returnArr['errorMsg']      = "";
            $returnArr['data']          = $data;
        } else {
            $returnArr['code']          = 401;
            $returnArr['status']        = 2;
            $returnArr['errorMsg']      = $result['ResultMsg'];
            $returnArr['data']          = array();
        }

       return $returnArr;
    }

    /**
     * 门诊缴费
     * @param $card_no   '就诊卡号'
     * @param $adv_id    '医嘱编号'
     * @param $fee       '缴费金额'
     * @param $bank_no   '缴费流水号'
     */
    public function outPatientPayAjax($param){

        $card_no            = $param['cardNo'];
        $medicineRetrun     = $param['medicineRetrun'];
        $medicineRetruninfo = json_decode($medicineRetrun,true);
        $adv_id             = $medicineRetruninfo['advId'];
        $fee                = $medicineRetruninfo['fee'];
        $bank_no            = $param['transaction_id'];

        $Content            = "<Request><CardNo>".$card_no."</CardNo><AdvId>".$adv_id."</AdvId><Fee>".$fee."</Fee><BillNo>".$bank_no."</BillNo><PayName>微信支付</PayName></Request>";
        $searchKey          = "Exc_Pay";
        $Result_K           = $searchKey."Result";
        $result             = $this->soapGetDate($searchKey, $Content, $Result_K);

        if ($result['ResultCode']  == 0) {
            $returnArr['code']     = 200;
            $returnArr['status']   = 1;
            $returnArr['errorMsg'] =$result['ResultMsg'];
            $returnArr['data']     = $result['Data']['item'];
        } else {
            $returnArr['code']     = 401;
            $returnArr['status']   = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data']     = array();
        }
        return $returnArr;
    }


    /**
     * @uses    就诊卡查询和绑定
     * @param   $params 参数
     * @author  Duanhy
     */
    public function cardInfoQueryAjax($params)
    {
        // TODO: Implement cardInfoQueryAjax() method.
    }

    /**
     * @uses    门诊就诊科室查询
     * @param   $params
     * @author  Duanhy
     */
    public function dutyDeptAjax($params)
    {
        // TODO: Implement dutyDeptAjax() method.
    }

    /**
     * @uses 门诊就诊科室医生查询
     * @param   $params
     * @author  Duanhy
     */
    public function dutyDoctorAjax($params)
    {
        // TODO: Implement dutyDoctorAjax() method.
    }

    /**
     * @uses 门诊就诊科室医生查询
     * @param   $params
     * @author  Duanhy
     */
    public function getDoctorSourceAjax($params)
    {
        // TODO: Implement getDoctorSourceAjax() method.
    }

    /**
     * @uses 取消预约 （锁号未支付） 定时任务
     * @param   $params
     * @author  Duanhy
     */
    public function cancelRegistrationAjax($params)
    {
        // TODO: Implement cancelRegistrationAjax() method.
    }

    /**
     * @uses 门诊缴费列表
     * @param   $params
     * @author  Duanhy
     */
    public function doctorAdviceAjax($params)
    {
        // TODO: Implement doctorAdviceAjax() method.
    }

    /**
     * @uses    生成门诊缴费订单
     * @param   $params
     * @author  Duanhy
     */
    public function preGeneratePayOrderAjax($params)
    {
        // TODO: Implement preGeneratePayOrderAjax() method.
    }

    /**
     * @uses    费生成订单
     * @param   $params
     * @author  Duanhy
     */
    public function GeneratePayOrderAjax($params)
    {
        // TODO: Implement GeneratePayOrderAjax() method.
    }

    /**
     * @uses    住院缴费列表
     * @param   $params
     * @author  Duanhy
     */
    public function getPayInfoAjax($params)
    {
        // TODO: Implement getPayInfoAjax() method.
    }

    /**
     * @uses    预交费生成订单
     * @param   $params
     * @author  Duanhy
     */
    public function createPayOrderAjax($params)
    {
        // TODO: Implement createPayOrderAjax() method.
    }

    /**
     * @uses    检查订单是否可以支付
     * @param   $params
     * @author  Duanhy
     */
    public function checkOrderAjax($params)
    {
        // TODO: Implement checkOrderAjax() method.
    }

    /**
     * @uses    提交订单
     * @param   $params
     * @author  Duanhy
     */
    public function prePayOrderSubmitAjax($params)
    {
        // TODO: Implement prePayOrderSubmitAjax() method.
    }

    /**
     * @uses    检验报告列表
     * @param   $params
     * @author  Duanhy
     */
    public function myExamineReportAjax($params)
    {
        // TODO: Implement myExamineReportAjax() method.
    }

    /**
     * @uses    检验报告详情
     * @param   $params
     * @author  Duanhy
     */
    public function myExamineReportResultAjax($params)
    {
        // TODO: Implement myExamineReportResultAjax() method.
    }

    /**
     * @uses    检查报告列表
     * @param   $params
     * @author  Duanhy
     */
    public function myInspectReportAjax($params)
    {
        // TODO: Implement myInspectReportAjax() method.
    }

    /**
     * @uses    检查报告详情
     * @param   $params
     * @author  Duanhy
     */
    public function myInspectReportResultAjax($params)
    {
        // TODO: Implement myInspectReportResultAjax() method.
    }

    /**
     * @uses    HIS对账接口
     * @param   $params
     * @author  Duanhy
     */
    public function BanlanceToWeixinAjax($params)
    {
        // TODO: Implement BanlanceToWeixinAjax() method.
    }
}